package com.abe.libquick.utils;

import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.ArrayAdapter;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.Spinner;

import com.abe.libcore.utils.CommonUtils;
import com.abe.libcore.utils.context.ContextUtils;
import com.abe.libquick.api.JsonHelper;
import com.abe.libquick.utils.quick.EmptyUtils;
import com.abe.libquick.utils.quick.ScreenUtils;
import com.abe.libquick.utils.quick.ToastTool;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.regex.Pattern;

import okhttp3.RequestBody;

public class NormalUtils {
    public static boolean fileIsCanReader(String path) {
        if (TextUtils.isEmpty(path)) return false;
        String type = getExtensionName(path);
        if (TextUtils.isEmpty(type)) return false;
        String[] types = {"doc", "docx", "ppt", "pptx", "xls", "xlsx", "pdf", "txt", "epub"};
        for (String s : types) {
            if (type.equals(s)) {
                return true;
            }
        }
        return false;
    }

    public static boolean isImage(String type) {
        if (TextUtils.isEmpty(type)) return false;
        String[] types = {"jpg", "jpeg", "png", "gif", "bmp"};
        for (String s : types) {
            if (type.equals(s)) {
                return true;
            }
        }
        return false;
    }

    public static boolean isVideo(String type) {
        if (TextUtils.isEmpty(type)) return false;
        String[] types = {"mp4", "avi", "rmvb", "wmv", "3gp", "flv", "rm"};
        for (String s : types) {
            if (type.equals(s)) {
                return true;
            }
        }
        return false;
    }

    /*
     * Java文件操作 获取文件扩展名
     * */
    public static String getExtensionName(String filename) {
        if ((filename != null) && (filename.length() > 0)) {
            int dot = filename.lastIndexOf('.');
            if ((dot > -1) && (dot < (filename.length() - 1))) {
                return filename.substring(dot + 1);
            }
        }
        return filename;
    }

    // 判断一个字符是否是中文
    public static boolean isChinese(char c) {
        return c >= 0x4E00 && c <= 0x9FA5;// 根据字节码判断
    }

    // 判断一个字符串是否含有中文
    public static boolean isContainChinese(String str) {
        if (TextUtils.isEmpty(str))
            return false;
        for (char c : str.toCharArray()) {
            if (isChinese(c))
                return true;// 有一个中文字符就返回
        }
        return false;
    }

    public static String keepTwo(String valueStr) {
        return keepFormat(valueStr);
    }

    public static String keepTwo(double value) {
        return keepFormat(value);
    }

    public static String keepFormat(String valueStr, int... num) {
        if (isNumber(valueStr)) {
            try {
                valueStr = keepFormat(Double.parseDouble(valueStr), num);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return valueStr;
    }

    public static String keepFormat(double value, int... num) {
        String rule = "#.";
        if (num.length > 0 && num[0] > 0) {
            for (int i = 0; i < num[0]; i++) {
                rule = String.format(Locale.CHINA, "%s%s", rule, "#");
            }
        } else {
            rule = "#.##";
        }
        DecimalFormat df = new DecimalFormat(rule);
        try {
            return df.format(value);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return String.valueOf(value);
    }

    //是否为整数或者浮点数
    public static boolean isNumber(String str) {
        if (TextUtils.isEmpty(str)) return false;
        return isDoubleOrFloat(str) || isNumeric(str);
    }

    /*
     * 是否为数字
     */
    public static boolean isNumeric(String str) {
        if (TextUtils.isEmpty(str)) return false;
        Pattern pattern = Pattern.compile("[0-9]*");
        return pattern.matcher(str).matches();
    }

    /*
     * 是否为浮点数？double或float类型。
     * @param str 传入的字符串。
     * @return 是浮点数返回true,否则返回false。
     */
    public static boolean isDoubleOrFloat(String str) {
        if (TextUtils.isEmpty(str)) return false;
        Pattern pattern = Pattern.compile("^[-\\+]?[.\\d]*$");
        return pattern.matcher(str).matches();
    }

    /**
     * 发送广播
     */
    public static void sendBroadcast(String action, Bundle bundle) {
        Intent intent = new Intent(action);
        intent.putExtras(bundle);
        ContextUtils.Companion.getContext().sendBroadcast(intent);
        CommonUtils.INSTANCE.log("action:" + action);
    }

    /**
     * 根据值, 设置spinner默认选中:
     */
    public static void setSpinnerItemSelectedByValue(Spinner spinner, String value) {
        ArrayAdapter<String> apsAdapter = (ArrayAdapter<String>) spinner.getAdapter();
        int k = apsAdapter.getCount();
        for (int i = 0; i < k; i++) {
            if (value.equals(apsAdapter.getItem(i))) {
                spinner.setSelection(i, true);// 默认选中项
                break;
            }
        }
    }

    /**
     * 动态设置ListView的高度
     *
     * @param listView listView
     */
    public static void setListViewHeightBasedOnChildren(ListView listView) {
        if (listView == null)
            return;
        ListAdapter listAdapter = listView.getAdapter();
        if (listAdapter == null) {
            return;
        }
        int totalHeight = 0;
        for (int i = 0; i < listAdapter.getCount(); i++) {
            View listItem = listAdapter.getView(i, null, listView);
            int desiredWidth = View.MeasureSpec.makeMeasureSpec(listView.getWidth(),
                    View.MeasureSpec.AT_MOST);
            listItem.measure(desiredWidth, 0);
            totalHeight += listItem.getMeasuredHeight();
        }
        ViewGroup.LayoutParams params = listView.getLayoutParams();
        params.height = totalHeight
                + (listView.getDividerHeight() * (listAdapter.getCount() - 1));
        listView.setLayoutParams(params);
    }

    /**
     * 动态设置listView的高度
     *
     * @param listView  指定的listView
     * @param itemHight 每行的高度
     */
    public static void setListViewHeightBasedOnChildren(ListView listView,
                                                        Integer itemHight) {

        ListAdapter listAdapter = listView.getAdapter();
        // item的高度
        int itemHeight = itemHight;
        if (listAdapter == null) {
            return;
        }
        int totalHeight = 0;
        for (int i = 0; i < listAdapter.getCount(); i++) {
            totalHeight += dip2px(listView.getContext(), itemHeight) + listView.getDividerHeight();
        }
        ViewGroup.LayoutParams params = listView.getLayoutParams();
        params.height = totalHeight;

        listView.setLayoutParams(params);
    }

    /**
     * 获取屏幕高宽比
     *
     * @param context context
     */
    public static float getDepthWidthRatio(Context context) {
        return (float) (getScreenHeight(context))
                / ((float) (getScreenWidth(context)));
    }

    /**
     * 获得屏幕宽度
     *
     * @param context context
     */
    public static int getScreenWidth(Context context) {
        WindowManager wm = (WindowManager) context
                .getSystemService(Context.WINDOW_SERVICE);
        DisplayMetrics outMetrics = new DisplayMetrics();
        wm.getDefaultDisplay().getMetrics(outMetrics);
        return outMetrics.widthPixels;
    }

    /**
     * 获得屏幕高度
     *
     * @param context context
     */
    public static int getScreenHeight(Context context) {
        WindowManager wm = (WindowManager) context
                .getSystemService(Context.WINDOW_SERVICE);
        DisplayMetrics outMetrics = new DisplayMetrics();
        wm.getDefaultDisplay().getMetrics(outMetrics);
        return outMetrics.heightPixels;
    }

    public static Uri getOutputMediaFileUri() {
        String path;
        File dir = new File(ConstantMBLib.CS_FILE + File.separator + "video");
        if (!dir.exists()) {
            if (!dir.mkdirs()) return null;
        }
        path = dir + "/VIDEO_" + System.currentTimeMillis() + ".mp4";
        File videoFile = new File(path);
        return Uri.fromFile(videoFile);
    }

    //获取video控件宽高
    public static int[] initNormalVideoWH() {
        int width = ScreenUtils.getScreenWidth() - dip2px(ContextUtils.Companion.getContext(), 20);
        int height = 9 * width / 16;
        return new int[]{width, height};
    }

    //根据文件名称获取文件类型（视频or图片）
    public static String getFJType(String fileName) {
        String type = "";
        String typeName = getFJTypeName(fileName);
        if (EmptyUtils.isNotEmpty(typeName)) {
            for (int i = 0; i < ConstantMBLib.FJ_TYPE_VIDEO_LIBS.length; i++) {
                if (typeName.equals(ConstantMBLib.FJ_TYPE_VIDEO_LIBS[i])) {
                    return ConstantMBLib.FJ_TYPE_VIDEO;
                }
            }
            for (int i = 0; i < ConstantMBLib.FJ_TYPE_IMAGE_LIBS.length; i++) {
                if (typeName.equals(ConstantMBLib.FJ_TYPE_IMAGE_LIBS[i])) {
                    return ConstantMBLib.FJ_TYPE_IMAGE;
                }
            }
        }
        return type;
    }

    //根据文件名称获取文件格式
    public static String getFJTypeName(String fileName) {
        if (EmptyUtils.isNotEmpty(fileName)) {
            String[] tempStrs = fileName.split("\\.");
            if (tempStrs.length > 1) {
                return tempStrs[tempStrs.length - 1];
            }
        }
        return "";
    }

    public static String providerAuthorities() {
        String providerAuthorities = (String) CommonUtils.INSTANCE.getMetaData(ContextUtils.Companion.getContext(),
                "provider_authorities", "");
        if (TextUtils.isEmpty(providerAuthorities)) {
            ToastTool.show("provider_authorities 未配置");
        }
        return providerAuthorities;
    }

    /**
     * 处理带反斜杠的json数据
     *
     * @param result 待处理数据
     */
    public static String getDecodeJSONStr(String result) {
        if (result.length() < 2) return result;
        // 声明中间变量进行处理
        String backlogJsonStrTmp = result.replace("\\", "");
        // 处理完成后赋值回去
        result = backlogJsonStrTmp.substring(1, backlogJsonStrTmp.length() - 1);
        return result;
    }

    public static RequestBody postBody(String json) {
        return RequestBody.create(okhttp3.MediaType.parse("application/json;charset=UTF-8"), json);
    }

    public static RequestBody postBody(Object o) {
        return RequestBody.create(okhttp3.MediaType.parse("application/json;charset=UTF-8")
                , JsonHelper.gson(JsonHelper.JSON_C_SHAPE).toJson(o));
    }

    public static boolean isHttpUrl(String url) {
        if (TextUtils.isEmpty(url)) {
            return false;
        } else if (url.length() < 4) {
            return false;
        } else return url.length() <= 4 || url.substring(0, 4).equals("http");
    }

    public static Date stringToDate(String rule, String dateStr) {
        if (TextUtils.isEmpty(rule) || TextUtils.isEmpty(dateStr)) return null;
        SimpleDateFormat format = new SimpleDateFormat(rule, Locale.CHINA);
        try {
            return format.parse(dateStr);
        } catch (ParseException e) {
            e.printStackTrace();
            return null;
        }
    }

    public static String dateToString(String rule, Date date) {
        if (TextUtils.isEmpty(rule) || date == null) return "";
        SimpleDateFormat format = new SimpleDateFormat(rule, Locale.CHINA);
        return format.format(date);
    }

    /**
     * 检查应用是否存在
     *
     * @param context     context
     * @param packageName packageName
     */
    public static boolean checkAPP(Context context, String packageName) {
        if (packageName == null || "".equals(packageName))
            return false;
        try {
            context.getPackageManager().getApplicationInfo(packageName,
                    PackageManager.GET_UNINSTALLED_PACKAGES);
            return true;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 判断是否返回成功
     *
     * @param statusCode statusCode
     */
    public static boolean isHttpSuccessExecuted(int statusCode) {
        return (statusCode > 199) && (statusCode < 400);
    }

    public static boolean saveFileInfo(String path, String data) {
        try {
            if (Environment.getExternalStorageState().equals(
                    Environment.MEDIA_MOUNTED)) {
                File dir = new File(ConstantMBLib.CS_FILE);
                if (!dir.exists()) {
                    boolean isSuccess = dir.mkdirs();
                    System.out.println(isSuccess);
                }
                FileOutputStream fos = new FileOutputStream(path);
                fos.write(data.getBytes());
                fos.close();
            }
            return true;
        } catch (Exception e) {
            Log.e("", "an error occured while writing file...", e);
        }
        return false;
    }

    public static String getFileInfo(String path) {
        try {
            FileInputStream inputStream = new FileInputStream(path);
            byte[] temp = new byte[1024];
            StringBuilder sb = new StringBuilder();
            int len;
            while ((len = inputStream.read(temp)) > 0) {
                sb.append(new String(temp, 0, len));
            }
            inputStream.close();
            return sb.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 根据手机的分辨率从 px(像素) 的单位 转成为 dp
     */

    public static int px2dip(Context context, float pxValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (pxValue / scale + 0.5f);
    }

    /**
     * 根据手机的分辨率从 dp 的单位 转成为 px(像素)
     */

    public static int dip2px(Context context, float dpValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }

    /**
     * 获取文件名及后缀
     */
    public static String getFileNameWithSuffix(String path) {
        if (TextUtils.isEmpty(path)) {
            return "";
        }
        int start = path.lastIndexOf("/");
        if (start != -1) {
            return path.substring(start + 1);
        } else {
            return "";
        }
    }
}